<template>
    <div>
        <div class="product">
            <h2>出库新增</h2>
            <el-form ref="form" :inline="true" :model="form" class="demo-form-inline" label-width="230px"
                style="margin:auto;width:80%;" :rules="rulesOut">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入名称"></el-input>
                </el-form-item>
                <el-form-item label="合作伙伴" prop="partnerId">
                    <!-- <el-input v-model="form.partnerId" placeholder="请输入合作伙伴"></el-input> -->
                    <el-select v-model="form.partnerId" filterable placeholder="请选择合作伙伴"
                        :filter-method="customerfilterMethod">
                        <el-option v-for="item in customerdata" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="交货日期" prop="scheduledDate">
                    <el-date-picker clearable v-model="form.scheduledDate" type="date" value-format="yyyy-MM-dd"
                        placeholder="请选择交货日期">
                    </el-date-picker>
                    <!-- <el-input v-model="form.scheduledDate" placeholder="请输入交货日期"></el-input> -->
                </el-form-item>

                <!-- <el-form-item label="付款条件">
                    <el-input v-model="form.scheduledDate" placeholder="审批人"></el-input>
                </el-form-item> -->
                <!-- <el-form-item label="出库入库" prop="moveType"> -->
                <!-- <el-radio v-model="form.moveType" label="outbound">出库</el-radio>
                    <el-radio v-model="form.moveType" label="warehousing">入库</el-radio> -->
                <!-- <el-input v-model="form.moveType" ></el-input> -->
                <!-- </el-form-item> -->

                <el-form-item label="备注">
                    <el-input v-model="form.origin" placeholder="请输入备注" width="300px"></el-input>
                </el-form-item>
                <!-- <el-form-item label="备注">
                    <el-input v-model="form.note" placeholder="请输入备注" width="300px"></el-input>
                </el-form-item> -->




            </el-form>
            <!-- 产品行表格 -->
            <div class="tab">
                <div class="btn">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="addorder">新增产品行</el-button>
                </div>
                <el-form :model="tableForm" ref="tableForm">
                    <el-table :data="tableForm.tableData" :row-class-name="rowSysGoodsIndex"
                        style="width: 90%; margin: 5px auto 30px;" border :header-cell-style="{ 'text-align': 'center' }"
                        :cell-style="{ 'text-align': 'center' }">
                        <el-table-column prop="sequence" label="序号">
                        </el-table-column>
                        <el-table-column prop="productTemplateId" label="产品名称" :render-header="req">
                            <template slot-scope="scope">
                                <el-form-item :prop="'tableData.' + scope.$index + '.productTemplateId'"
                                    :rules="rules.productTemplateId">
                                    <el-select clear v-model="scope.row.productTemplateId" filterable placeholder="请选择产品"
                                        @change="stockidFun" :filter-method="stockfilterMethod">
                                        <el-option v-for="item in stockdata" :key="item.id" :label="item.name"
                                            :value="parseInt(item.id)">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column prop="productQty" label="实际数量">
                            <template slot-scope="scope">
                                <el-form-item :prop="'tableData.' + scope.$index + '.productQty'" :rules="rules.productQty">
                                    <el-input v-model="scope.row.productQty" :disabled="true"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column prop="orderedQty" label="数量" :render-header="req">
                            <template slot-scope="scope">
                                <el-form-item :prop="'tableData.' + scope.$index + '.orderedQty'" :rules="rules.orderedQty">
                                    <el-input v-model.number="scope.row.orderedQty"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>

                        <el-table-column prop="note" label="说明">
                            <template slot-scope="scope">
                                <el-form-item :prop="'tableData.' + scope.$index + '.note'">
                                    <el-input v-model="scope.row.note"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>

                        <!-- <el-table-column prop="productMinQty" label="表面处理">
                </el-table-column>
                <el-table-column prop="productMaxQty" label="备注">
                </el-table-column> -->
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="orderUpdate(scope.row)"
                                    v-hasPermi="['system:stock:edit']">修改</el-button> -->
                                <el-button size="mini" type="text" icon="el-icon-success"
                                    @click="ordersub(scope.row)">确认</el-button>
                                <el-button size="mini" type="text" icon="el-icon-delete"
                                    @click="orderDel(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                </el-form>
            </div>
            <!-- 整体提交按钮 -->
            <div class="sub">
                <el-button type="info" @click="cancelsubmit" style="width:150px">放弃提交</el-button>
                <el-button type="primary" @click="submit" style="width:150px">提交</el-button>

            </div>
        </div>
        <!-- 产品行新增 -->
        <el-dialog :title="title" :visible.sync="orderzz" width="800px" append-to-body>
            <el-form ref="form1" :model="form1" :rules="rules" label-width="150px">
                <el-form-item label="产品" prop="productTemplateId">
                    <el-select v-model="form1.productTemplateId" filterable placeholder="请选择产品"
                        :filter-method="stockfilterMethod" @change="stockidFun">
                        <el-option v-for="item in stockdata" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="实际数量" prop="productQty">
                    <el-input v-model.number="form1.productQty" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="数量" prop="orderedQty">
                    <el-input v-model.number="form1.orderedQty" placeholder="请输入数量"></el-input>
                </el-form-item>

                <el-form-item label="说明" prop="note">
                    <el-input v-model="form1.note" placeholder="请输入说明"></el-input>
                </el-form-item>



            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="orderForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 产品行修改 -->
        <el-dialog :title="title" :visible.sync="orderzzedit" width="800px" append-to-body>
            <el-form ref="form2" :model="form2" :rules="rules" label-width="150px">
                <el-form-item label="产品" prop="name">
                    <el-select v-model="form2.name" filterable placeholder="请选择产品" :filter-method="stockfilterMethod"
                        @change="stockidFun">
                        <el-option v-for="item in stockdata" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="实际数量" prop="productQty">
                    <el-input v-model.number="form2.productQty" placeholder="请输入数量" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="数量" prop="orderedQty">
                    <el-input v-model.number="form2.orderedQty" placeholder="请输入数量"></el-input>
                </el-form-item>

                <el-form-item label="说明" prop="note">
                    <el-input v-model="form2.note" placeholder="请输入说明"></el-input>
                </el-form-item>



            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="editsuborderForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { listPartner } from '@/api/system/partner.js'

import { listStock } from '@/api/system/stock.js'
import { Addmaterialreturnnote, addorderzz, addPicking, delorderzz, editorderzz, editorderzzsub, cancelsale, czstock } from '@/api/system/picking.js'

import materialreturnnote from "@/views/system/materialreturnnote/index";
export default {
    data() {
        return {

            // 修改产品行表单参数
            form2: {},
            // 修改产品行弹框
            orderzzedit: false,

            // 用来存储赋值给tabledata
            stockMoveList: [],
            // 外层合作伙伴名称表单验证
            rulesOut: {
                partnerId: [
                    { required: true, message: "合作伙伴不能为空", trigger: ["blur", 'change'] }
                ],
                scheduledDate: [
                    { required: true, message: "交货日期不能为空", trigger: "blur" }
                ],
                moveType: [
                    { required: true, message: "出库入库不能为空", trigger: "blur" }
                ],
                name: [
                    { required: true, message: "名称不能为空", trigger: "blur" }
                ],

            },
            // 产品行校验
            rules: {
                productTemplateId: [
                    { required: true, message: "产品不能为空", trigger: ["blur", 'change'] }
                ],
                orderedQty: [
                    { required: true, message: "订购数量不能为空", trigger: "blur" },
                    { type: 'number', message: '订购数量必须为数字值' }
                ],
                worldchampCurrency: [
                    { required: true, message: "币种不能为空", trigger: "blur" }
                ],
                //     isTax:[
                // {required: true, message: "是否含税不能为空", trigger:"blur"}
                //     ],
                //     isProvideFreight:[
                // {required: true, message: "是否承担运费不能为空", trigger:"blur"}
                //     ],
                //     deliveryConditionsId:[
                // {required: true, message: "交货条件不能为空", trigger:"blur"}
                //     ],
            },
            title: '',
            // 产品行弹框
            orderzz: false,
            // 产品数组

            stockdata: []
            ,
            // 外层表单参数
            form: {},
            // 新增产品行表单参数
            form1: {
                productQty: null,

                orderedQty: null,
                // productId:null

            },
            tableForm: {
                tableData: []
            },
            /// 查询合作伙伴参数,用于下拉框
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: null,
                date: null,
                vat: null,
                website: null,
                comment: null,
                creditLimit: null,
                active: null,
                customer: 't',
                supplier: null,
                employee: null,
                type: null,
                street: null,
                zip: null,
                city: null,
                stateId: null,
                countryId: null,
                email: null,
                phone: null,
                mobile: null,
                isCompany: null,
                partnerShare: null,
                commercialPartnerId: null,
                commercialCompanyName: null,
                writeUid: null,
                writeDate: null,
                customerCode: null,
                deliveryAddress: null
            },
            // 合作伙伴下拉框
            customerdata: [],
        };
    },
    mounted() {
        let query = this.$route.query;
        this.getSaleOrderWrite(query)
        this.stockList()
        this.customerList()
    },
    methods: {
        // 订单行确认
        ordersub(row) {
            // console.log(this.tableForm);
            this.$refs["tableForm"].validate((valid) => {
                // console.log(valid);
                if (valid) {
                    const id = row.sequence - 1
                    // console.log(id);
                    // console.log(this.tableForm.tableData);
                    // const arr = []
                    // arr.push(this.tableForm.tableData[id])
                    this.form.saleOrderParts = this.tableForm.tableData
                    // console.log(this.form);
                    // Addmaterialreturnnote(this.form).then(res => {
                    //     console.log(res);
                    // this.form = res.data
                    // this.tableForm.tableData = res.data.saleOrderParts
                    // this.amountTotalDaxie = res.data.amountTotalDaxie
                    // this.amountTotal = res.data.amountTotal

                    // })
                }
            })
        },
        /** 商品序号 */
        rowSysGoodsIndex({ row, rowIndex }) {
            row.sequence = rowIndex + 1;
        },
        req(h, colunm) {
            // console.log(h);
            // console.log(colunm);
            // console.log(colunm.column.label);
            return [
                h('span', { style: 'color:#f56c6c' }, '*'),
                h('span', ' ' + colunm.column.label)
            ]

        },
        // 放弃提交
        cancelsubmit() {
            this.$modal.confirm('是否确认放弃新增出库，并且清空已填写的内容').then(function () {
                return cancelsale().then({})
            }).then(() => {

                this.$modal.msgSuccess("已清除刚才所填写的内容");
                this.$router.push({
                    path: "/materialreturnnote",
                    component: materialreturnnote,
                    redirect: "noRedirect",
                    hidden: false,
                    alwaysShow: true,
                });
            }).catch((err) => {
                // console.log(err);
                // this.$message("新增失败");
            });


        },
        // 出库提交
        submit() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    //   alert('submit!');
                    this.form.stockMoveList = this.tableForm.tableData
                    // console.log(this.form);
                    const aa = this.form
                    // quotationsub(this.form).then(res => {
                    //     console.log(res);
                    // })
                    this.$modal.confirm('是否确认新增出库').then(function () {
                        return addPicking(aa).then(res => {
                            // console.log(res);
                            const id = Number(res.data)
                            czstock(id).then(res => {
                                // console.log(res);
                            })
                        })
                    }).then(() => {
                        // this.getList();
                        // this.getStkBomPart(stockid)
                        this.$modal.msgSuccess("新增成功");
                        this.$router.push({
                            path: "/materialreturnnote",
                            component: materialreturnnote,
                            redirect: "noRedirect",
                            hidden: false,
                            alwaysShow: true,
                        });
                    }).catch((err) => {
                        // console.log(err);
                        this.$message("新增失败");
                    });
                } else {
                    // console.log('error submit!!');
                    return false;
                }
            });

        },
        // 清空产品行
        reset() {
            this.form1 = {
                productQty: null,
                orderedQty: null,
                name: null,
                // productId:null

            }
        },
        // 点击新增销售订单跳转后请求
        getSaleOrderWrite(query) {
            Addmaterialreturnnote(query).then(res => {
                // console.log(res);
                this.form = res.data
                this.stockMoveList = res.data.stockMoveList
                this.tableData = res.data.stockMoveList

                // this.form.moveType = res.data.moveType

            })
        },
        // 选择产品赋值
        stockidFun(e) {
            // console.log(e);
            addorderzz(e).then(res => {
                // console.log(res);
                const arr = this.tableForm.tableData.map(item => {
                    // return item.sequence==this.tableForm.tableData.length
                    if (item.sequence === this.tableForm.tableData.length) {
                        item.productQty = res.data[0].productQty
                        item.name = res.data[0].name
                        item.productId = res.data[0].productId
                        item.orderedQty = res.data[0].orderedQty

                    }
                })
                // this.form1.productQty = res.data[0].productQty
                // this.form1.orderedQty = res.data[0].orderedQty
                // this.form1.name = res.data[0].name
                // this.form1.productId = res.data[0].productId
            })
        },
        // 下拉框选择产品组件,用于下拉框显示默认十条
        stockList() {
            listStock(this.stockquery).then(res => {
                // console.log(res);
                this.stockdata = res.rows
                // console.log(this.stockdata);

            })
        },
        // 产品搜索，用于直接在下拉框搜索
        stockfilterMethod(node, val) {
            // console.log(node, val);
            const que = {
                name: node,
                pageSize: 100
            }
            // console.log(que);
            listStock(que).then(res => {
                // console.log(res);
                this.stockdata = res.rows
            })
        },
        // 点击新增产品行触发
        addorder() {
            // this.orderzz = true
            // this.reset()
            let obj = {};
            obj.productTemplateId = "";
            obj.productQty = "";
            obj.orderedQty = "";
            obj.note = "";
            // console.log(this.tableForm.tableData);
            if (this.tableForm.tableData === null) {
                this.tableForm.tableData = []
            }
            this.tableForm.tableData.push(obj);
        },
        // 下拉框选择合作伙伴
        customerList() {
            listPartner(this.queryParams).then(res => {
                // console.log(res);
                this.customerdata = res.rows
                // console.log(this.customerdata);
                this.form.moveType = 'outbound'

            })

        },
        // 合作伙伴搜索
        customerfilterMethod(node, val) {

            // console.log('val', val, 'node', node)
            // console.log(node);
            const que = {
                name: node,
                pageSize: 100,
                customer: 't'
            }
            // console.log(que);
            listPartner(que).then(res => {
                // console.log(res);
                this.customerdata = res.rows
            })
        },
        // 取消按钮
        cancel() {
            this.orderzz = false;
            this.orderzzedit = false;
            // this.Bomadd = false;
            //   this.reset();
        },
        // 产品行新增提交
        orderForm() {
            // this.Bomform.stockId = this.$route.query.listId;
            // this.Bomform.productQty = Number(this.Bomform.productQty)
            // console.log(this.Bomform);
            this.$refs["form1"].validate(valid => {
                if (valid) {
                    // console.log(this.stockMoveList);
                    // console.log(this.form1);
                    // console.log(this.form);
                    if (this.stockMoveList === null) { this.stockMoveList = [] }
                    // this.stockMoveList=[]
                    this.stockMoveList.push(this.form1)
                    this.form.stockMoveList = this.stockMoveList
                    // console.log(this.stockMoveList);
                    // console.log(this.form);
                    Addmaterialreturnnote(this.form).then(res => {
                        // console.log(res);
                        this.orderzz = false
                        this.tableData = res.data.stockMoveList
                        this.form = res.data

                    })
                    //         //   if (this.form.id != null) {
                    //         //     updateStock(this.form).then(response => {
                    //         //       this.$modal.msgSuccess("修改成功");
                    //         //       this.open = false;
                    //         //       this.getList();
                    //         //     });
                    //         //   } else {
                    //         addBomPart(this.Bomform).then(response => {
                    //             this.$modal.msgSuccess("新增成功");
                    //             this.Bomadd = false;
                    //             //   this.getList();
                    //             this.getStkBomPart(this.Bomform.stockId)
                    //         });
                    //         //   }
                }
            });
        },
        // 点击删除产品行触发
        orderDel(row) {
            const that = this
            // console.log(row);
            const id = row.sequence
            // this.delorder(id)
            this.$modal.confirm('是否确认删除产品名称为"' + row.name + '"的数据项？').then(function () {
                return that.delorder(id)
            }).then(() => {
                // this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch((err) => {
                // console.log(err);
            });

        },
        // 删除产品行接口方法
        delorder(id) {
            // console.log(id);
            delorderzz(id).then(res => {
                // console.log(res);
                // console.log(this.stockMoveList);
                this.stockMoveList = res.data.stockMoveList
                this.form = res.data
                // console.log(this.form);
                // console.log(this.form.deliveryConditionsId);
                this.tableData = res.data.stockMoveList
                this.amountTotalDaxie = res.data.amountTotalDaxie
                this.amountTotal = res.data.amountTotal
            })
        },
        // 点击编辑产品行触发
        orderUpdate(row) {
            const id = row.sequence
            this.orderzzedit = true
            editorderzz(id).then(res => {
                // console.log(res);
                this.title = '修改产品行'
                this.form2 = res.data

            })
        },
        // 编辑产品行提交
        editsuborderForm() {
            // console.log(this.form2);
            editorderzzsub(this.form2).then(res => {
                // console.log(res);
                this.stockMoveList = res.data.stockMoveList
                this.form = res.data
                this.tableData = res.data.stockMoveList
                this.amountTotalDaxie = res.data.amountTotalDaxie
                this.amountTotal = res.data.amountTotal
                this.orderzzedit = false
            })
        },
    },
    components: {},
    props: {},
    watch: {},
    computed: {},
    created() { },
};
</script>
<style lang="scss" scoped>
.product {
    width: 80%;
    background: #fff;
    border: 1px rgb(232, 228, 228) solid;
    // box-shadow: 0 3px 20px -15px #000000;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin: 10px auto;
}

h2 {
    text-align: center;
    line-height: 60px;
}

.btn {
    margin-left: 5%;
}

.sub {
    // width: 80%;
    // border: 1px red solid;
    text-align: center;
    margin-bottom: 20px;

}

.total {

    // border: 1px red solid;
    width: 90%;
    margin: 50px auto;

    // margin: 40px 60% 30px;
    // border-top: 2px gray solid;
    // text-align:right;
    .totalright {
        width: 30%;
        // float: right;
        margin-left: 70%;
        border-top: 2px gray solid;

        p {
            line-height: 40px;
            text-align: right;
        }
    }

}

.thRed {
    // height: 200px;
    margin-top: 22px;
}
</style>